package com.zhaotianhao.gatewayserver.filter;

import cn.hutool.json.JSONException;
import cn.hutool.jwt.JWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @Author Z-7
 * @Date 2022/5/16
 */
@Slf4j
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取路由信息
        Route route = (Route)exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        System.out.println(route.getId());
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        // 登录方法放行
        if (path.toString().endsWith("/user/login")) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        try {
            JWT jwt = JWT.of(token).setKey("zhao".getBytes());
            if (!jwt.validate(0)) {
                log.error("token过期");
                // 未授权
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            // token 合法
            Object username = jwt.getPayload("username");
            redisTemplate.opsForValue().set("login:"+token,username);
        } catch (JSONException jsonException) {
            jsonException.printStackTrace();
            log.error("token异常");
            // 未授权
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 合法 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
